package com.lsmw.ucenter.controller;


import com.alibaba.nacos.api.annotation.NacosInjected;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lsmw.commonutils.MD5;
import com.lsmw.commonutils.ParseR;
import com.lsmw.commonutils.R;
import com.lsmw.ucenter.client.MyAdminClient;
import com.lsmw.ucenter.entity.LsUCenterMember;
import com.lsmw.ucenter.entity.vo.RegisterVo;
import com.lsmw.ucenter.service.LsUCenterMemberService;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author 二号男嘉宾
 * @since 2020-12-24
 */
@CrossOrigin
@RestController
@RequestMapping("/uCenter/member")
public class LsUCenterMemberController {

    private LsUCenterMemberService memberService;
    private MyAdminClient myAdminClient;

    @NacosInjected
    public LsUCenterMemberController(MyAdminClient myAdminClient) {
        this.myAdminClient = myAdminClient;
    }

    @Autowired
    public void setMemberService(LsUCenterMemberService memberService) {
        this.memberService = memberService;
    }

    @ApiOperation("会员登录")
    @PostMapping("/login")
    public R loginUser(@RequestBody LsUCenterMember member, HttpServletResponse response) {
        String token = memberService.login(member);
        return R.ok().data("token", token).setResponseCode(response);
    }

    @ApiOperation("会员注册")
    @PostMapping("/register")
    public R registerUser(@RequestBody RegisterVo registerVo, HttpServletResponse response) {
        return memberService.register(registerVo) ? R.created().setResponseCode(response) : R.invalidRequest().setResponseCode(response);
    }

    @ApiOperation(value = "添加用户")
    @PostMapping("/")
    public R addUser(
            @ApiParam(name = "UserInfo", value = "用户数据(json)", required = true)
            @RequestBody LsUCenterMember lsUCenterMember) {
        if (!memberService.list(new LambdaQueryWrapper<LsUCenterMember>()
                .eq(LsUCenterMember::getMobile,lsUCenterMember.getMobile())).isEmpty()){
            return R.invalidRequest().data("msg","此手机号已注册过!");
        }
        lsUCenterMember.setPassword(MD5.encrypt(lsUCenterMember.getPassword()));
        return memberService.save(lsUCenterMember) ? R.created() : R.invalidRequest();
    }

    @ApiOperation("获取会员信息")
    @GetMapping("/memberInfo")
    public R getMemberInfo(HttpServletRequest request, HttpServletResponse response) {
        return R.ok().data("memberInfo", memberService.getMemberInfo(request)).setResponseCode(response);
    }

    //超级管理员根据昵称模糊查询（排除逻辑删除条件）
    @ApiOperation("超级管理员根据昵称模糊查询")
    @GetMapping("/findMembersByNickname_superAdmin")
    public R findMembersByNickname_superAdmin(
            @ApiParam(name = "nickname", value = "模糊昵称")
            @RequestParam("nickname") String nickname,
            @ApiParam(name = "adminId", value = "超级管理员id")
            @RequestParam("adminId") String adminId,
            HttpServletResponse response) {
        R adminById = myAdminClient.getAdminById(adminId); // 远程调用通过id获取管理员信息的方法

        ParseR.Admin admin = new ParseR().new Admin(adminById);
        if (!admin.isMsg()) {
            if (!admin.getAdminAuth()) {
                //如果为超级管理员就调用排除逻辑删除的方法
                return memberService.findMembersByNickname_superAdmin(nickname).setResponseCode(response);

            }
            return memberService.findMembersByNickname_Admin(nickname).setResponseCode(response);
        }
        return adminById;
    }

    @ApiOperation(value = "根据昵称查询用户信息")
    @GetMapping("nickname/{name}/{current}/{limit}")
    public R getUserInfoById(
            @ApiParam(name = "name", value = "昵称", required = true) @PathVariable String name,
            @ApiParam(name = "current", value = "当前页下标", required = true) @PathVariable long current,
            @ApiParam(name = "limit", value = "每页记录数", required = true) @PathVariable long limit) {
        Page<LsUCenterMember> userPage = new Page<>(current, limit);
        if (name == Character.toString('0')) {
            memberService.page(userPage, new LambdaQueryWrapper<LsUCenterMember>()
                    .select(LsUCenterMember.class, qw -> !qw.getColumn().equals("password")));
        } else {
            memberService.page(userPage, new LambdaQueryWrapper<LsUCenterMember>()
                    .like(LsUCenterMember::getNickname, name)
                    .select(LsUCenterMember.class,qw -> !qw.getColumn().equals("password")));
        }
        return R.ok().data("rows", userPage.getRecords()).data("total", userPage.getTotal());
    }

    @ApiOperation(value = "根据ID删除用户")
    @DeleteMapping("/{id}")
    public R removeUserById(
            @ApiParam(name = "id", value = "用户id", required = true)
            @PathVariable String id) {
        return memberService.deleteMemberById(id);
    }

    @ApiOperation(value = "根据ID修改用户信息")
    @PutMapping("/{id}")
    public R updateUserById(
            @ApiParam(name = "id", value = "用户id", required = true)
            @PathVariable String id,
            @ApiParam(name = "lsHotelInfo", value = "酒店数据(json)", required = true)
            @RequestBody LsUCenterMember lsUCenterMember) {
        lsUCenterMember.setPassword(MD5.encrypt(lsUCenterMember.getPassword()));
        return memberService.updateById(lsUCenterMember) ? R.created() : R.notFound();
    }

    @ApiOperation(value = "根据ID获取用户信息")
    @GetMapping("user/{id}")
    public R getUserById(
            @ApiParam(name = "id", value = "用户id", required = true)
            @PathVariable String id) {
        LsUCenterMember lsUCenterMember;
        lsUCenterMember = memberService.getById(id);
        lsUCenterMember.setPassword("");
        return R.ok().data("row", lsUCenterMember);
    }

    @ApiOperation(value = "获取用户手机号")
    @GetMapping("user/phone/{phone}")
    public R getPhoneNum(
            @ApiParam(name = "phone", value = "手机号", required = true)
            @PathVariable String phone) {
        LsUCenterMember lsUCenterMember;
        lsUCenterMember = memberService.getOne(new LambdaQueryWrapper<LsUCenterMember>().eq(LsUCenterMember::getMobile,phone));
        return lsUCenterMember == null ?R.ok().data("phone", false):R.ok().data("phone", true);
    }

    //管理员根据id删除会员
    @ApiOperation("管理员根据id删除会员")
    @DeleteMapping("/deleteMemberById")
    public R deleteMemberById(
            @ApiParam(name = "memberId", value = "会员id")
            @RequestParam("memberId")
                    String memberId,
            @ApiParam(name = "adminId", value = "管理员id")
            @RequestParam("adminId")
                    String adminId) {
        R adminById = myAdminClient.getAdminById(adminId); // 远程调用通过id获取管理员信息的方法
        ParseR.Admin admin = new ParseR().new Admin(adminById);
        if (admin.isMsg()) {
            return adminById;
        }
        return memberService.deleteMemberById(memberId);
    }

    //管理员根据多个id删除会员
    @ApiOperation("管理员根据多个id删除会员")
    @DeleteMapping("/deleteMemberByIds")
    public R deleteMemberByIds(
            @ApiParam(name = "memberIds", value = "多个会员id")
            @RequestParam("memberIds")
                    String memberIds,
            @ApiParam(name = "adminId", value = "管理员id")
            @RequestParam("adminId")
                    String adminId) {
        R adminById = myAdminClient.getAdminById(adminId); // 远程调用通过id获取管理员信息的方法
        ParseR.Admin admin = new ParseR().new Admin(adminById);
        if (admin.isMsg()) {
            return adminById;
        }

        String[] split = memberIds.split(",");
        List<String> list = new ArrayList<>();
        for (String s : split) {
            list.add(s);
        }
        return memberService.deleteMemberByIds(list);
    }

    @ApiOperation(value = "分页查询")
    @GetMapping("/pageUser/{current}/{limit}")
    public R getHotelListPage(
            @ApiParam(name = "current", value = "当前页下标", required = true) @PathVariable long current,
            @ApiParam(name = "limit", value = "每页记录数", required = true) @PathVariable long limit) {
        Page<LsUCenterMember> userPage = new Page<>(current, limit);
        memberService.page(userPage, new LambdaQueryWrapper<LsUCenterMember>()
                .select(LsUCenterMember.class,qw -> !qw.getColumn().equals("password")));
        Map map = new HashMap<>();
        map.put("total", userPage.getTotal());
        map.put("rows", userPage.getRecords());
        return R.ok().data(map);
    }

}

